const axios = require('axios')
const moment = require('moment')
const uuidv4 = require('uuid/v4')
const random = require('string-random')
function fetch(url) {
    return new Promise(async (resolve, reject) => {
        try {
            const result = await axios.get(url)
            resolve(result)
        } catch (error) {
            reject(error)
        }
    })
}


function setZero(num){
    return  ("0" + num).slice(-2);
}

function createAppId() {
    return "Ble" + random(16)
}
function createAppsecret() {
    return uuidv4()
}
function todayStart() {
    return new Date(
        new Date(new Date().toLocaleDateString()).getTime()
    )
}
function todayEnd() {
    return new Date( // 当天23:59
        new Date(new Date().toLocaleDateString()).getTime() +
        24 * 60 * 60 * 1000 -
        1
    )
}

function startDateTime(time) {
    const nowTimeDate = new Date(time);
    return new Date(nowTimeDate.setHours(0, 0, 0, 0));
    //return new Date (new Date(nowTimeDate.setHours(0, 0, 0, 0)).getTime() + ATime);
}

function endDateTime(time) {
    const nowTimeDate = new Date(time)
    return new Date(nowTimeDate.setHours(23, 59, 59, 999));
    //return new Date (new Date(nowTimeDate.setHours(23, 59, 59, 999)).getTime() + ATime);
}

function startTime(time) {
    const nowTimeDate = new Date(time)
    const ATime = 8 * 60 * 60 * 1000;
    return new Date(nowTimeDate.setHours(0, 0, 0, 0));
    //return new Date(nowTimeDate.setHours(0, 0, 0, 0).getTime() + ATime)
}
// const start = new Date(new Date(new Date().toLocaleDateString()).getTime());
// //console.log(start); //Mon Dec 04 2017 00:00:00 GMT+0800 (中国标准时间)
// const end = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1);
// //console.log(end); //Mon Dec 04 2017 23:59:59 GMT+0800 (中国标准时间)
function endTime(time) {
    const nowTimeDate = new Date(time)
    const ATime = 8 * 60 * 60 * 1000;
    return new Date(nowTimeDate.setHours(23, 59, 59, 999));
   // return new Date(nowTimeDate.setHours(23, 59, 59, 999).getTime() + ATime);
}

/**
 * 获取倒退天 日期
 * @param  {[type]} date [description]
 * @param  {[type]} day  [description]
 * @return {[type]}      [description]
 */
function getFallbackDate(date,day){
    day = parseInt(day);
    return new Date( // 
        date.getTime() -
        day * 24 * 60 * 60 * 1000
    )
}

function getFallbackWeek(time,number) {
    const nowTimeDate = new Date(time);
    let date = new Date(nowTimeDate.setHours(0, 0, 0, 0));
    return moment(date).day(-6).add(-number,'weeks').toDate();
}
function getFallbackMonth(time,number) {
    const nowTimeDate = new Date(time);
    let date = new Date(nowTimeDate.setHours(0, 0, 0, 0));
    return moment(date).set('date',1).add(-number,'months').toDate();
}
function getFallbackYear(time,number) {
    const nowTimeDate = new Date(time);
    let date = new Date(nowTimeDate.setHours(0, 0, 0, 0));
    return moment(date).set('month',0).set('date',1).add(-number,'years').toDate();
}


function getYesterdayStart() {
    return new Date(getDay(-1, '-'))
}
function getYesterdayEnd() {
    return new Date(new Date(getDay(-1, '-')).getTime() + 24 * 60 * 60 * 1000 -
        1)
}
function getWeekStart() {
    return new Date(getDay(-6, '-'))
}
function getWeekEnd() {
    return new Date(new Date(getDay(0, '-')).getTime() + 24 * 60 * 60 * 1000 -
        1)
}
//console.log(' getWeekStart():', getWeekStart())
function getRandom(m, n) {
    return Math.floor(Math.random() * (m - n) + n)
}

function getRandNum() {
    let day = new Date()
    const rand = getRandom(1, 9)
    // console.log('rand:', rand)
    const num = moment(new Date()).format("YYYYMMDDhhmm") + '' + rand
    //console.log('num:', num.length)
    return num
}
//getRandNum()

function getOrderId(n) {
    let m =getRandom(1, 9) + n
    // console.log('m:', m)
    // console.log('m:', m.length)
    const orderId = getRandNum() + m
    //  console.log('orderId:', orderId)
    //  console.log('orderId:', orderId.length)
    return parseInt(orderId)
}

function randomNumber(count) {
  let str = "",
    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

  for (let i = 0; i < count; i++) {
    let pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}

function checkPhone(phone){
    var myreg=/^1[3456789]\d{9}$/;
    if (!myreg.test(phone)) {
        return false;
    }else{
        return true;
    }
}

function getDateFormat(date){
    return  moment(date).format('YYYY-MM-DD HH:mm:ss');
}

function getDateFormat2(date){
    return  moment(date).format('YYYY-MM-DD');
}



function getOrderNo(number = 5){
    let orderNo = moment(new Date()).format('YYYYMMDDhhmmss')+randomNumber(number);
    console.log("orderNo:",orderNo);
    return orderNo;
}

//判断数值是否为空
function isNull(value){
    return !value || value == undefined || String(value).trim() == '';
}


/**
*随机数据
*/
function getUuidCode(count = 16){
    var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var nums="";
    for(var i=0;i<count;i++){
        var id = parseInt(Math.random()*61);
        nums+=chars[id];
    }
    return nums;
}

/**
 * 或者链接的绝对地址 去除域名
 * @param  {[type]} url [description]
 * @return {[type]}     [description]
 */
function getUrlAbsolute(url){
     return '/' + url.split('/').slice(3).join('/');
}

function  numSub(num1, num2) {
    var baseNum, baseNum1, baseNum2;
    var precision;// 精度
    try {
      baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
      baseNum1 = 0;
    }
    try {
      baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
      baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
    return (Number((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(2))+ '';
}


function numAdd(num1, num2) {//加法
    var baseNum, baseNum1, baseNum2;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
}

function getTimeStamp(){
    const timeStamp =Math.floor(new Date().getTime()/1000).toString()
    return timeStamp;
}

function getDiffDate(startTime,endTime){
    
    let dateList = [];
    let nowTime = new Date(startTime.getTime());
    while((endTime.getTime()-nowTime.getTime())>=0){
        var year = nowTime.getFullYear();
        var month = nowTime.getMonth() + 1;

        var month = month.toString().length==1?"0"+month.toString():month;
        var day = nowTime.getDate().toString().length==1?"0"+nowTime.getDate():nowTime.getDate();
        dateList.push(year+"-"+month+"-"+day);
        nowTime.setDate(nowTime.getDate()+1);
    }
    return dateList;
}


function getNextMonth(date) {

    var year = date.getFullYear(); //获取当前日期的年份
    var month = date.getMonth() + 1; //获取当前日期的月份
    var day = date.getDate(); //获取当前日期的日
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
        year = parseInt(year) + 1;
        month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year + '-' + month2 + '-' + day2;
    return new Date(t2);
}

function getDiffMonth(startTime,endTime){
    let monthList = [];
    let lastTime = new Date(new Date(endTime.getTime()).setDate(1));
    let nowTime = new Date(new Date(startTime.getTime()).setDate(1));
    while((lastTime.getTime()-nowTime.getTime())>=0){
        var year = nowTime.getFullYear();
        var month = nowTime.getMonth() + 1;

        var month = month.toString().length==1?"0"+month.toString():month;
        monthList.push(year+"-"+month);
        nowTime = getNextMonth(nowTime);
    }
    return monthList;
}

function mobileCheck(string) {  
    var pattern = /^1\d{10}$/;  
    if (pattern.test(string)) {  
        return true;  
    }  
    return false;  
}; 


//console.log("getOrderId(n)",getOrderId(3285))

module.exports = {
    fetch,
    createAppId,
    createAppsecret,
    todayStart,
    todayEnd,
    getOrderId,
    randomNumber,
    getOrderNo,
    isNull,
    checkPhone,
    getUuidCode,
    getUrlAbsolute,
    numSub,
    numAdd,
    getTimeStamp,
    startTime,
    endTime,
    getFallbackDate,
    getDiffDate,
    getDiffMonth,
    getDateFormat,
    startDateTime,
    endDateTime,
    getDateFormat2,
    getFallbackWeek,
    getFallbackMonth,
    getFallbackYear,
    mobileCheck,
    setZero
}